package com.sxm.yiwei.activitis;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.sxm.yiwei.R;
import com.sxm.yiwei.adapters.BillAdapter;
import com.sxm.yiwei.adapters.CryBookAdapter;
import com.sxm.yiwei.beans.CryBookSq;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.tools.IsLogin;
import com.sxm.yiwei.tools.MySQManager;
import com.sxm.yiwei.tools.MySqHelper;
import com.sxm.yiwei.tools.SqData;
import com.sxm.yiwei.utils.InternetAddressUtis;
import com.sxm.yiwei.views.MyListview;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class CryActivity extends BaseActivity implements View.OnClickListener{

    private ImageView cryback;
    private ImageView hopeImg;
    private MyListview crybookList;
    private String id;
    private SharedPreferences sharedPreferences;
    private String appId;
    private String userId;
    private String token;

    private String type;
    private MySqHelper helper;
    private ScrollView cryscroll;
    private CryBookAdapter cryBookAdapter;
    private ImageView nodata;
    private ImageView backmain;
    private int TYPE = 3000;
    private String uid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cry);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        appId = sharedPreferences.getString("appid","1");
        userId = sharedPreferences.getString("userId", "0");
        token = sharedPreferences.getString("token", "");
        Intent intent = getIntent();
        id = intent.getStringExtra("id");

        cryscroll = (ScrollView) findViewById(R.id.cry_scroll);
        cryscroll.smoothScrollTo(0,0);
        initCryView();

        if (token.equals("")){

            nodata.setVisibility(View.VISIBLE);

        }else {
           // nodata.setVisibility(View.GONE);
        }

       List list = initData();
       initListview(list);

    }

        //提取数据
    private List initData() {
        List<CryBookSq> mList = new ArrayList();
        helper = MySQManager.getInstance(CryActivity.this);

        SQLiteDatabase db = helper.getWritableDatabase();

        Cursor cursor = db.query("yivic", null, null, null, null, null, SqData.ID +" desc");
        while (cursor.moveToNext()){

            String intro = cursor.getString(cursor.getColumnIndex("intro"));
            String ordercode = cursor.getString(cursor.getColumnIndex("code"));
            String orderid = cursor.getString(cursor.getColumnIndex("oid"));
            String uid = cursor.getString(cursor.getColumnIndex("uid"));
            String time = cursor.getString(cursor.getColumnIndex("time"));
            String totalamount = cursor.getString(cursor.getColumnIndex("amount"));

            long l = System.currentTimeMillis();
            Long l1 = Long.valueOf(time);
            if (l-l1>259200000){
                String where ="time =?";
                db.delete("yivic",where,new String[]{time});
            }else {

            }
            int type = cursor.getInt(cursor.getColumnIndex(SqData.TYPE));
            CryBookSq cryBookSq = new CryBookSq();
            cryBookSq.setIntro(intro);
            cryBookSq.setOrderCode(ordercode);
            cryBookSq.setOrderId(orderid);
            cryBookSq.setPublishTime(time);
            cryBookSq.setTotalAmount(totalamount);
            cryBookSq.setUid(uid);
            cryBookSq.setType(type);
            mList.add(cryBookSq);
        }
        db.close();
        return mList;
    }

    // 添加list view
    private void initListview(final List list) {
        if (token.equals("")){
            if (list.size()==0){
                nodata.setImageResource(R.mipmap.jsj);
            }else {
                nodata.setVisibility(View.GONE);
            }
        }else {
            if (list.size()==0){
                nodata.setImageResource(R.mipmap.nodata);
            }else {
                nodata.setVisibility(View.GONE);
            }
        }

        cryBookAdapter = new CryBookAdapter(this,list);
        crybookList.setAdapter(cryBookAdapter);

        cryBookAdapter.setOnClick(new CryBookAdapter.Callback() {
            @Override
            public void onclick(int v) {
                if (IsLogin.isLogin()) {
                    CryBookSq item = (CryBookSq) list.get(v);
                    uid = item.getUid();
                    if (userId==""){
                        IsLogin.isLogin();
                    }else {
                        if (uid.equals(userId)){
                            Toast.makeText(CryActivity.this, "这是您自己的订单，自己不可以抢哦", Toast.LENGTH_SHORT).show();
                        }else {
                            cryBook(item);
                        }
                    }


                }else {}
            }

            @Override
            public void onclickItem(int v) {
                CryBookSq cryBookSq = (CryBookSq) cryBookAdapter.getItem(v);
                String orderId = cryBookSq.getOrderId();
                String uid1 = cryBookSq.getUid();
                int type = cryBookSq.getType();
               switch (type){
                   case 1:
                       break;
                   case 2:
                       Intent intent = new Intent(CryActivity.this,BookContentHotActivity.class);
                       intent.putExtra("id",orderId);
                       intent.putExtra("uid", uid1);
                       intent.putExtra("TYPE",TYPE);
                       startActivity(intent);
                      break;
                   case 3:
                       Intent intent3 = new Intent(CryActivity.this,BookContentHelpActivity.class);
                       intent3.putExtra("id",orderId);
                       intent3.putExtra("uid", uid1);
                       intent3.putExtra("TYPE",TYPE);
                       startActivity(intent3);
                       break;
               }

            }

        });
        cryBookAdapter.notifyDataSetChanged();
    }

    private void initCryView() {
        cryback = (ImageView) findViewById(R.id.cry_back);
        backmain = (ImageView) findViewById(R.id.cry_backmain);
        hopeImg = (ImageView) findViewById(R.id.cry_hopeimg);
        crybookList = (MyListview) findViewById(R.id.crybook_list);
        nodata = (ImageView) findViewById(R.id.cry_nodata);

        backmain.setOnClickListener(this);
        cryback.setOnClickListener(this);
        nodata.setOnClickListener(this);
                hopeImg.setOnClickListener(this);

        }

        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.cry_back:
                    finish();
                    break;
                case R.id.cry_nodata:
                    IsLogin.isLogin();
                break;
            case R.id.cry_hopeimg:
                // 跳转到可抢红包详情页面
              //  startActivity(new Intent(CryActivity.this,CryHopeActivity.class));
                Toast.makeText(this, "功能建设中，敬请期待", Toast.LENGTH_SHORT).show();
                break;
        }
    }
public void cryBook(CryBookSq item){
    final String orderId = item.getOrderId();

    final int type1 = item.getType();
    // 提示抢单
    AlertDialog.Builder b = new AlertDialog.Builder(CryActivity.this);
    View view = LayoutInflater.from(CryActivity.this).inflate(R.layout.crybook_dialogitem, null);
    b.setView(view);
    Button no = (Button) view.findViewById(R.id.dialog_no);
    Button yes = (Button) view.findViewById(R.id.dialog_yes);
    final AlertDialog dialog = b.create();
    no.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
    yes.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View v) {

            // 发送请求 提示成功
            RequestParams params = new RequestParams(InternetAddressUtis.Url + InternetAddressUtis.CRYBOOK);
            params.addHeader("Content-Type", "application/json");
            params.addHeader("token", token);
            params.addHeader("appId", appId);
            params.addHeader("userId", userId);
            JSONObject object = new JSONObject();
            object.put("orderId", orderId);
            params.setBodyContent(object.toJSONString());
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    AlertDialog.Builder bu = new AlertDialog.Builder(CryActivity.this);
                    View view1 = LayoutInflater.from(CryActivity.this).inflate(R.layout.crybook_okdialogitem, null);
                    bu.setView(view1);
                    Button okbt = (Button) view1.findViewById(R.id.dialog_okbt);
                    TextView message = (TextView) view1.findViewById(R.id.crybook_message);
                    final AlertDialog dialog1 = bu.create();
                    JSONObject obj1 = JSON.parseObject(result);
                    String status = obj1.getString("status");
                    if (status.equals("0")) {
                        String failure = obj1.getString("failure");
                        if (failure.equals("1028")) {
                            message.setText("您来晚了 订单已经被抢走了");
                        }else if(failure.equals("1011")){
                            message.setText("您提交的一喂员认证正在审核中，请耐心等待");
                        } else if (failure.equals("1029")) {
                            message.setText("为保证物品的安全,请申请一喂员,级别达到小工以上,才可以抢单");
                        } else if (failure.equals("1027")) {
                            message.setText("为保证物品的安全,请申请一喂员,级别达到小工以上,才可以抢单");
                        } else if (failure.equals("1030")) {
                            message.setText("此订单已您已经抢过了，再看看别的订单吧");
                        } else if (failure.equals("1032")) {
                            message.setText("订单已被对方取消，去看看别的订单吧");
                        } else if (failure.equals("1021")) {
                            message.setText("为保证物品的安全，级别达到小工以上才可以抢单 ");
                        } else if (failure.equals("10210")) {
                            message.setText("此单保价高于您的可接单额度(200),为保证物品的安全,需要达到小工级别以上才可以抢单 ");
                        } else if (failure.equals("10211")) {
                            message.setText("此单保价高于您的可接单额度(500),为保证物品的安全,需要达到贫农级别以上才可以抢单");
                        } else if (failure.equals("10212")) {
                            message.setText("此单保价高于您的可接单额度(1000),为保证物品的安全,需要达到富农级别以上才可以抢单");
                        } else if (failure.equals("10213")) {
                            message.setText("此单保价高于您的可接单额度(5000),为保证物品的安全,需要达到地主级别以上才可以抢单");
                        } else if (failure.equals("10214")) {
                            message.setText("此单保价高于您的可接单额度(1w),为保证物品的安全,需要达到知县级别以上才可以抢单");
                        } else if (failure.equals("10215")) {
                            message.setText("此单保价高于您的可接单额度(2w),为保证物品的安全,需要达到知府级别以上才可以抢单");
                        } else if (failure.equals("10216")) {
                            message.setText("此单保价高于您的可接单额度(5w),为保证物品的安全,需要达到总督级别以上才可以抢单");
                        } else if (failure.equals("10217")) {
                            message.setText("此单保价高于您的可接单额度(10w),为保证物品的安全,需要达到王爷级别以上才可以抢单");
                        } else if (failure.equals("10218")){
                            message.setText("为保证订单的时效性，请您距离订单20公里内再抢");

                        }
                        okbt.setText("确定");
                        okbt.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog1.dismiss();
                            }
                        });
                    } else {
                        String data = obj1.getString("data");
                        JSONObject obj2 = JSON.parseObject(data);
                        String grabStatus = obj2.getString("grabStatus");

                        if (grabStatus.equals("0")) {
                            okbt.setText("确定");

                            message.setText("抢单成功，请等待选定吧");
                            okbt.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(CryActivity.this, OrderSelectActivity.class);
                                    startActivity(intent);
                                    dialog1.dismiss();
                                }
                            });
                        } else {
                            okbt.setText("去取货");
                            message.setText("抢单成功，快上门取货吧");
                            okbt.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(CryActivity.this, OrderPickupActivity.class);

                                    startActivity(intent);
                                    dialog1.dismiss();
                                }
                            });
                        }
                    }
                    dialog1.show();
                    dialog.dismiss();
                    SQLiteDatabase db = helper.getWritableDatabase();
                    String where = "oid = ?";
                    db.delete("yivic", where, new String[]{orderId});
                    db.close();

                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    Log.d("tag", "onError: 你好抢单" +
                            "-0--"+ex);
                    ErrType.errType(CryActivity.this, ex);
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });

        }
    });
    dialog.show();
}


}
